import { Variable } from "@/api/interface/iot";
import { getHistoryDataList } from "@/api/modules/iot/data";
import { getPageList } from "@/api/modules/iot/variable";
import BaseChart from "@/components/Chart/BaseChart.vue";
import { DataChart } from "@/components/Chart/interface";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { shortcuts } from "@/hooks/useTime";
// import { SchemaNodeKey } from "@/utils/constants";
// import { parseProfileFromSn } from "@/utils/schema";
import { dayjs } from "element-plus";
import { defineComponent } from "vue";
export default defineComponent({
	props: {
		sn: String,
		title: String,
		dataValue: [String, Number, Object, Array],
		height: {
			type: String,
			default() {
				return "400px";
			}
		},
		dataKey: {
			type: String,
			default() {
				//key path: k1, k1.k1_1
				return "k1";
			}
		}
	},
	emits: [],
	setup(props, { attrs }) {
		const chartView = ref<any>();
		const viewType = ref<string>();
		const viewTypeList = ref<{ label: string; value: string }[]>([
			{ label: "图表", value: "chart" },
			{ label: "列表", value: "list" }
		]);
		/* eslint-disable  */
		const variableInfo = ref<Variable.ResVariable>({ sn: "", key: "", type: "", label: "", config: {} });
		const initParam = reactive({ pageIndex: 0, pageSize: 20 });
		const proTable = ref<any>();
		let chartDataList: any = [];
		const active = ref<string>("");
		const stats = reactive<any>({
			timeRange: []
		});
		// if (typeof props.dataValue == "number") {
		viewType.value = "chart";
		// } else {
		// 	viewType.value = "list";
		// }
		const loadSensorInfo = () => {
			getPageList({ sn: props.sn || "", keys: props.dataKey || "", pageIndex: 1, pageSize: 1 }).then(({ result }) => {
				variableInfo.value = result.records?.[0] || {};
				changeView();
			});
		};
		const feachHistory = async (params?: any) => {
			//判断变量是否在数组中
			let arr = props.dataKey.split(".");
			let startArr: string | any[] = [];
			let endArr: string | any[] = [];
			//截取第一个数组位置
			arr.some((item: any, index: number) => {
				if (index != 0 && (!!Number(item) || Number(item) == 0)) {
					startArr = arr.slice(0, index);
					endArr = arr.slice(index, arr.length);
					return true;
				}
			});
			let obj = stats.timeRange.length
				? {
						startTime: dayjs(stats.timeRange[0]).format("YYYY-MM-DD HH:mm:ss"),
						endTime: dayjs(stats.timeRange[1]).format("YYYY-MM-DD HH:mm:ss")
				  }
				: {};
			if (stats.timeRange.length && viewType.value == "chart") {
				delete params.pageIndex;
				delete params.pageSize;
			}
			let res: any = await getHistoryDataList({
				idSn: props.sn || "",
				key: startArr.length ? startArr.toString().replaceAll(",", ".") : props.dataKey,
				keyType: "sensor", //sensor、system,
				...params,
				...obj,
				// startTime: stats.timeRange[0]
				// 	? dayjs(stats.timeRange[0]).format("YYYY-MM-DD HH:mm:ss")
				// 	: dayjs().format("YYYY-MM-DD 00:00:00"),
				// endTime: stats.timeRange[1]
				// 	? dayjs(stats.timeRange[1]).format("YYYY-MM-DD HH:mm:ss")
				// 	: dayjs().format("YYYY-MM-DD 23:59:59"),
				timeOrder: "desc" //viewType.value == "chart" ? "" : "desc"
			});
			if (res.result) {
				let dataList = (stats.timeRange.length ? res.result : res.result.records) || [];
				//如果变量存在数组中就去取对应位置的值
				if (endArr.length) {
					let str = "";
					endArr.map((endItem: any) => {
						str += `['${endItem}']`;
					});
					chartDataList = dataList.map((item: any) => {
						item.value = item.value ? eval(`item.value${str}`) : null;
						return item;
					});
				} else {
					chartDataList = dataList;
				}
			} else {
				chartDataList = [];
			}
			return res;
		};
		const changeView = () => {
			nextTick(async () => {
				if (viewType.value == "chart") {
					await feachHistory({ pageIndex: 1, pageSize: 1000 });
					if (chartDataList.length) {
						chartDataList.reverse();
					}
					convertChart();
				} else {
					// await feachHistory({ pageIndex: 1, pageSize: 20 });
					proTable.value.getTableList();
				}
			});
		};
		watchEffect(() => {
			active.value = props.dataKey;
			loadSensorInfo();
		});
		const convertChart = () => {
			//转换成图表需要的数据格式
			//测试数据
			// let dataList = [
			// 	{
			// 		devSn: "device000001",
			// 		id: 1,
			// 		updateTime: "2023-02-14 09:19:25",
			// 		value: 23.2
			// 	},
			// 	{
			// 		devSn: "device000001",
			// 		id: 1,
			// 		updateTime: "2023-02-14 09:20:25",
			// 		value: 23.2
			// 	}
			// ];
			let chartData: DataChart.DataList = { dataList: [] };
			if (chartDataList.length) {
				let fmt = "YYYY-MM-DD HH:mm:ss";
				let st = dayjs(chartDataList[0].updateTime).format("YYYY-MM-DD");
				let et = dayjs(chartDataList[chartDataList.length - 1].updateTime).format("YYYY-MM-DD");
				if (st == et) {
					fmt = "HH:mm:ss";
				}
				chartDataList.map((item: any) => {
					item.valKey = active.value;
					let dts = dayjs(item.updateTime);
					let time = dts.isValid() ? dts.format(fmt) : item.updateTime;
					chartData.dataList.push({
						time: time,
						value: item.value,
						group: variableInfo.value.label,
						unit: variableInfo.value.config?.unit
					});
				});
				let seen = new Map();
				chartData.dataList = chartData.dataList.filter((item: any) => {
					return !seen.has(item.time) && seen.set(item.time, 1);
				});
				chartView.value?.setData(chartData);
			} else {
				chartView.value?.setData([]);
			}
		};
		const columns: ColumnProps[] = [
			{ prop: "devSn", label: "设备" },
			{ prop: "key", label: "变量" },
			{ prop: "updateTime", label: "时间" },
			{ prop: "value", label: "数据值" },
			{ prop: "unit", label: "单位" }
		];
		const dataCallback = (data: any) => {
			if (variableInfo.value.config?.unit) {
				data.records.map((item: any) => (item.unit = variableInfo.value.config?.unit));
			}
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};
		return () => {
			return (
				<div>
					<div class="flex justify-between p-4">
						<div class="pl-4">
							<el-radio-group v-model={viewType.value} onChange={() => changeView()} size="large">
								{viewTypeList.value.map(item => {
									return <el-radio label={item.value}>{item.label}</el-radio>;
								})}
							</el-radio-group>
						</div>
						<div>
							<span class="pr-2">时间范围</span>
							<el-date-picker
								v-model={stats.timeRange}
								style="width:340px"
								type="datetimerange"
								shortcuts={shortcuts()}
								range-separator="至"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								onChange={() => changeView()}
							/>
							<el-button class="iconfont iconbx-sync" style="margin-top:-5px" onClick={() => changeView()}>
								查询
							</el-button>
						</div>
					</div>
					{viewType.value == "chart" ? (
						<BaseChart class="pl-4 pr-4 pb-6 bg-white" ref={chartView} {...attrs} height="55vh" />
					) : (
						<div style="height:55vh">
							<ProTable
								initParam={initParam}
								ref={proTable}
								showHeader={false}
								columns={columns}
								requestApi={feachHistory}
								dataCallback={dataCallback}
							></ProTable>
						</div>
					)}
				</div>
			);
		};
	}
});
